local P = ClassFromFile(...)

local mqttManager = MqttManagerEx.New()
P.serverId = 0


function P.Init(serverId)
    P.serverId = serverId
    MqttHelper.Connect("114.115.217.64", "client|"..KBEngineLua.serverId.."|"..tostring(KBEngineLua.player().dbid), "username", "password", System.Action_bool(P.OnConnect))
end

function P.OnConnect(success)
    if success then
        log("Mqtt connect success!")
        local topics = {ChatTopicType.allServer, ChatTopicType.singleServer..tostring(P.serverId)}
        P.Subscribe(topics)
    else
        logError("Mqtt connect failed!")
    end
end

function P.Connect(host, clientId, userName, password, connectCallback)
    mqttManager:Connect(host, clientId, userName, password, connectCallback)
    mqttManager.receiveMsgCallback = System.Action_string_object(P.OnReceiveMsg)
end

function P.Publish(topic, msg)
    mqttManager:Publish(topic, msg, false)
end

function P.Subscribe(topics)
    mqttManager:Subscribe(topics)
end

function P.Unsubscribe(topics)
    mqttManager:Unsubscribe(topics)
end

function P.Disconnect()
    mqttManager:Disconnect()
end

function P.OnReceiveMsg(topic, msg)
    local msgType = 0
    if topic == ChatTopicType.allServer then
        msgType = MsgType.allServer
    elseif topic == ChatTopicType.singleServer..tostring(P.serverId) then
        msgType = MsgType.singleServer
    end
    KBEngineLua.player():Net_ReceiveMsg(0, msgType, msg)
end